package cn.gavin.web.controller;

import cn.gavin.domain.Permission;
import cn.gavin.qo.JsonResult;
import cn.gavin.qo.QueryObject;
import cn.gavin.service.IPermissionService;
import cn.gavin.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;


@Controller
@RequestMapping("/permission")
public class PermissionController {
    @Autowired
    private IPermissionService permissionService;

    @RequiredPermission(name = "权限页面",expression = "permission:list")
    @RequestMapping("/list")
    public String list(Model model, QueryObject qo){
        model.addAttribute("pageInfo",permissionService.query(qo));
        return "permission/list";
    }

    @RequiredPermission(name = "权限删除",expression = "permission:delete")
    @RequestMapping("/delete")
    public String delete(Long id){
        if (id != null) {
            permissionService.deleteById(id);
        }
        return "redirect:/permission/list";
    }

/*
    @RequestMapping("/input")
    public String input(Long id,Model model){
        if (id != null) {
            Permission permission = permissionService.findById(id);
            model.addAttribute("permission",permission);
        }
        return "permission/input";
    }
*/

    @RequestMapping("/save")
    public String save(Permission permission){
        if (permission.getId() != null) {
            permissionService.update(permission);
        }else {
            permissionService.insert(permission);
        }
        return "redirect:/permission/list";
    }

    @RequiredPermission(name = "权限加载",expression = "permission:reload")
    @RequestMapping("/reload")
    @ResponseBody
    public JsonResult reload(){
        try {
//            int a = 1/0;
            permissionService.reload();
            return new JsonResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new JsonResult(false,"权限加载失败");
        }
    }
}
